package com.hmdp.interceptor;

import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.hmdp.dto.UserDTO;
import com.hmdp.utils.UserHolder;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

/**
 * @Author: dupeng
 * @CreateTime: 2024-10-22  17:13
 * @Description: token刷新拦截器
 */
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate){
        this.stringRedisTemplate = stringRedisTemplate;
    }

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        //检查是否携带token
        String token = request.getHeader("authorization");
        if (StringUtils.isBlank(token)) {
            return true;
        }

        //根据token获取用户
        UserDTO user = JSONUtil.toBean(stringRedisTemplate.opsForValue().get(token), UserDTO.class);
        if (Objects.isNull(user)) {
            return true;
        }

        //保存用户至ThreadLocal
        UserHolder.saveUser(user);

        //重置token过期时间
        stringRedisTemplate.expire(token, 30L, TimeUnit.MINUTES);

        //放行
        return true;


    }


    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //移除用户
        UserHolder.removeUser();
    }
}
